<template>
	<view style="width: 100%;height: 100%;">
		<view :id="mapId" class="mapDiv" :prop="option" :change:prop="Trenderjs.initTMap"></view>
	</view>
</template>

<script>
	import tools from '../../tools.js'
	import iconPath from '../../static/point.png'

	export default {
		name: 'TianDiTu-Map',
		data() {
			return {
				Tmap: null,
				option: {
					type: '',
					apikey: '',
					lng: '',
					lat: '',
					png: iconPath,
					mapId: ''
				}
			}
		},
		props: {
			apiKey: {
				type: String,
				require: true,
				default: ''
			},
			customIcon: {
				type: String,
				default: ''
			},
			mapId: {
				type: String,
				default () {
					return 'mapDiv_' + Math.floor(Math.random() * 1000000)
				}
			}
		},
		methods: {
			compliteonLoadTianDiTu() {
				this.$emit('onLoadTianDiTu')
			},
			initCharts(lng, lat) {
				console.log('tianditu-map:initCharts called with', lng, lat)
				this.option = {
					apikey: this.apiKey,
					lng,
					lat,
					png: this.customIcon || this.option.png,
					type: 'open',
					mapId: this.mapId
				}
			},
			upDataCharts(lng, lat) {
				console.log('tianditu-map:upDataCharts called with', lng, lat)
				this.option = {
					...this.option,
					type: 'update',
					lng,
					lat,
					png: this.customIcon || this.option.png,
					mapId: this.mapId
				}
			},
			async nextPoint(lnglat) {
				var that = this;
				let params = {
					postStr: JSON.stringify({
						lon: lnglat.lng,
						lat: lnglat.lat,
						ver: 1,
					}),
					type: 'geocode',
					tk: that.apiKey
				}
				let resData = await tools.createRequest('https://api.tianditu.gov.cn/geocoder', params, true)
				if (resData && (resData.status === '0' || resData.status === 0)) {
					const info = tools.formatterAdressLocation(resData.result, 1)
					this.option = {
						...this.option,
						apikey: this.apiKey,
						lng: lnglat.lng,
						lat: lnglat.lat,
						png: this.customIcon || this.option.png,
						type: 'update'
					}
					this.$emit('onSelect', info)
				} else {
					tools.createMessage('数据异常', 1000, false, 'error')
				}
			}
		}
	}
</script>


<script module="Trenderjs" lang="renderjs">
	var Tmap = null;
	var _currentMarker = null;
	export default {
		data() {
			return {
				options: {},
			}
		},
		mounted() {
			// if (typeof window.T === 'object') {
			//     console.warn('--------天地图已加载--------');
			// } else {
			//     if (this.apiKey) {
			//         const script = document.createElement('script')
			//         script.src = 'https://api.tianditu.gov.cn/api?v=4.0&tk=' + this.apiKey
			//         script.onload = this.initChartsRender.bind(this)
			//         document.head.appendChild(script)
			//     }
			// }
		},
		methods: {
			initTMap(newValue, oldValue, ownerInstance, instance) {
				this.options = newValue
				if (newValue.type === 'open' && newValue.apikey) {
					if (!window.T) {
						const script = document.createElement('script')
						script.src = 'https://api.tianditu.gov.cn/api?v=4.0&tk=' + this.options.apikey
						script.onload = this.initChartsRender.bind(this)
						document.head.appendChild(script)
					} else {
						const {
							lng,
							lat
						} = this.options
						Tmap = null;
						const mapId = this.options.mapId || 'mapDiv'
						Tmap = new T.Map(mapId, {
							projection: 'EPSG:4326',
						});
						Tmap.centerAndZoom(new T.LngLat(lng, lat), 15);
						this.setIcon(lng, lat, true)
						this.$ownerInstance.callMethod('nextPoint', {
							lng,
							lat
						})
						Tmap.addEventListener('click', (e) => {
							this.$ownerInstance.callMethod('nextPoint', e.lnglat)
						});
					}
				} else {
					const {
						lng,
						lat
					} = newValue
					this.upDataChartsRender(lng, lat)
				}
			},
			initChartsRender() {
				console.log('tianditu-map:initChartsRender called, options=', this.options)
				this.$ownerInstance.callMethod('compliteonLoadTianDiTu')
				const {
					lng,
					lat
				} = this.options
				var that = this;
				const mapId = this.options.mapId || 'mapDiv'
				Tmap = new T.Map(mapId, {
					projection: 'EPSG:4326',
				});
				Tmap.centerAndZoom(new T.LngLat(lng, lat), 15);
				this.setIcon(lng, lat, true)
				this.$ownerInstance.callMethod('nextPoint', {
					lng,
					lat
				})
				Tmap.addEventListener('click', (e) => {
					this.$ownerInstance.callMethod('nextPoint', e.lnglat)
				});
			},
			upDataChartsRender(lng, lat) {
				if (!Tmap) return
				this.setIcon(lng, lat, true)
				Tmap.centerAndZoom(new T.LngLat(lng, lat), 15);
			},
			setIcon(lng, lat, isClear) {
				if (!Tmap) return;
				try {
					// 如果要求清空所有覆盖物，则先清空
					if (isClear) {
						Tmap.clearOverLays()
						_currentMarker = null
					}
					// 如果已经存在单个 marker，则移除它（只移除我们添加的 marker）
					if (_currentMarker) {
						try {
							Tmap.removeOverLay(_currentMarker)
						} catch (e) {
							/* ignore if API differs */ }
						_currentMarker = null
					}

					// 默认内联 SVG（红点），用于在自定义图标不可用时保证可见性
					var defaultSvg =
						'<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30"><circle cx="15" cy="15" r="6" fill="#e53935"/></svg>';
					var iconUrl = this.options.png || ('data:image/svg+xml;utf8,' + encodeURIComponent(defaultSvg));
					// 若 iconUrl 是相对路径（以 / 开头），在 H5 上可直接使用；否则尝试保留原样
					console.debug('tianditu-map: final iconUrl=', iconUrl)
					const icon = new T.Icon({
						iconUrl: iconUrl,
						iconSize: new T.Point(30, 30),
						iconAnchor: new T.Point(15, 30)
					});
					console.debug('tianditu-map:setIcon using iconUrl=', iconUrl)
					let marker
					try {
						marker = new T.Marker(new T.LngLat(lng, lat), {
							icon
						});
						Tmap.addOverLay(marker);
						_currentMarker = marker
					} catch (errMarker) {
						console.warn('使用自定义图标创建 marker 失败，尝试使用默认 marker', errMarker)
						try {
							// 回退：不传 icon，使用默认系统标记
							marker = new T.Marker(new T.LngLat(lng, lat));
							Tmap.addOverLay(marker);
							_currentMarker = marker
						} catch (err2) {
							console.error('回退创建默认 marker 也失败', err2)
						}
					}
				} catch (err) {
					console.error('setIcon error', err)
				}
			},
		},
	}
</script>

<style scoped>
	.mapDiv {
		width: 100%;
		height: 100%;
	}

	::v-deep .tdt-control-copyright {
		display: none;
	}
</style>